using System;
using JNPF.Basics.Models;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using JNPF.Utils;
using System.Transactions;
using Microsoft.EntityFrameworkCore.Metadata.Internal;
using NPOI.POIFS.FileSystem;

namespace JNPF.Basics.Logic
{
    public class jiushiCustomerconsultantBll
    {
        private jiushiCustomerconsultantIService service = new jiushiCustomerconsultantService();



        private CustomerbaseIService customerbaseService = new CustomerbaseService();


        private UserextendIService userextendService = new UserextendService();


        private UserIService userService = new UserService();

        private CustomeruserIService customeruserIService = new CustomeruserService();



        private jiushiCustomerconsultantdetailIService customerconsultantdetailService = new jiushiCustomerconsultantdetailService();

        /// <summary>
        /// 获取信息
        /// </summary>
        /// <param name="id">主键值</param>
        /// <returns></returns>
        public async Task<CustomerconsultantEntity> GetInfo(int id)
        {
            try
            {
                return await service.GetInfo(id);
            }
            catch (Exception ex)
            {
                throw ExceptionEx.Throw(ex);
            }
        }


        /// <summary>
        /// 获取信息
        /// </summary>
        /// <param name="id">主键id</param>
        /// <returns></returns>
        public async Task<CustomerconsultantEntity> GetInfoByUuid(string uuid)
        {
            try
            {
                return await service.GetInfoByUuid(uuid);
            }
            catch (Exception ex)
            {
                throw ExceptionEx.Throw(ex);
            }

        }



        /// <summary>
        /// 获取信息
        /// </summary>
        /// <param name="customerId">主键值</param>
        /// <returns></returns>
        public async Task<CustomerconsultantEntity> GetInfoByCustomerId(int customerId)
        {
            try
            {
                return await service.GetInfoByCustomerId(customerId);
            }
            catch (Exception ex)
            {
                throw ExceptionEx.Throw(ex);
            }
        }


        /// <summary>
        /// 获取信息
        /// </summary>
        /// <param name="id">主键值</param>
        /// <returns></returns>
        public async Task<jiushiCustomerconsultantListOutput> GetInfoResult(int id)
        {
            try
            {
                return await service.GetInfoResult(id);
            }
            catch (Exception ex)
            {
                throw ExceptionEx.Throw(ex);
            }
        }

        /// <summary>
        /// 获取列表
        /// </summary>
        /// <param name="input">请求参数</param>
        /// <returns></returns>
        public async Task<PageResult<CustomerconsultantEntity>> GetPageList(jiushiCustomerconsultantListQueryInput input)
        {
            try
            {
                return await service.GetPageList(input);
            }
            catch (Exception ex)
            {
                throw ExceptionEx.Throw(ex);
            }
        }

        /// <summary>
        /// 获取列表
        /// </summary>
        /// <param name="input">请求参数</param>
        /// <returns></returns>
        public async Task<PageResult<jiushiCustomerconsultantListOutput>> GetCusPageList(jiushiCustomerconsultantListQueryInput input)
        {
            try
            {
                return await service.GetCusPageList(input);
            }
            catch (Exception ex)
            {
                throw ExceptionEx.Throw(ex);
            }
        }


        /// <summary>
        /// 新建积分
        /// </summary>
        /// <param name="entity">实体对象</param>
        /// <returns></returns>
        public async Task Create(jiushiCustomerconsultantCrInput input)
        {
            try
            {
                CustomerconsultantEntity entity = new CustomerconsultantEntity();
                if (entity != null && input.id > 0)
                {
                    entity = await service.GetInfo(input.id.Value);
                    entity.Number++;
                }
                else
                {
                    entity.Uuid = Guid.NewGuid().ToString("N");
                    entity.CustomerId = input.customerId;
                    entity.Number = 1;

                    entity.Amount = input.amount;
                    entity.SortCode = 1;
                    entity.EnabledMark = 1;
                    entity.CreatorTime = DateTime.Now;
                    entity.CreatorUserId = UserProvider.Instance.Get().UserId;
                    entity.DeleteMark = 0;
                }
                //客户信息
                CustomerbaseEntity customerbaseEntity = await customerbaseService.GetInfo(entity.CustomerId.Value);

                //信贷管家
                CustomeruserEntity customeruserEntity = await customeruserIService.GetInfo(customerbaseEntity.Id, 1);

                CustomerconsultantdetailEntity customerconsultantdetail = new CustomerconsultantdetailEntity();
                customerconsultantdetail.SortCode = 1;
                customerconsultantdetail.EnabledMark = 1;
                customerconsultantdetail.CreatorTime = DateTime.Now;
                customerconsultantdetail.CreatorUserId = UserProvider.Instance.Get().UserId;
                customerconsultantdetail.Type = 0;

                customerconsultantdetail.CreatorUser = UserProvider.Instance.Get().UserName;
                customerconsultantdetail.DeleteMark = 0;
                customerconsultantdetail.Uuid = entity.Uuid;
                customerconsultantdetail.Amount = input.amount;
                customerconsultantdetail.PartnerUserId = entity.PartnerUserId;
                customerconsultantdetail.PartnerPoint = 0;
                customerconsultantdetail.AttachmentInfo = input.attachmentInfo;
                customerconsultantdetail.ParentPartnerUserId = entity.ParentPartnerUserId;
                customerconsultantdetail.ParentUserPoint = customerconsultantdetail.PartnerPoint * entity.DrawProportion / 100;
                customerconsultantdetail.UserId = customeruserEntity.UserId;



                //修改数据
                await service.Create(entity, customerconsultantdetail);
            }
            catch (Exception ex)
            {
                throw ExceptionEx.Throw(ex);
            }
        }

        /// <summary>
        /// 审核积分
        /// </summary>
        /// <param name="entity">实体对象</param>
        /// <returns></returns>
        public async Task CxamineCreate(int detailId)
        {
            try
            {
                //子表信息
                CustomerconsultantdetailEntity customerconsultantdetail = await customerconsultantdetailService.GetInfo(detailId);
                //查询父表信息
                CustomerconsultantEntity entity = await service.GetInfoByUuid(customerconsultantdetail.Uuid);

                //客户信息
                CustomerbaseEntity customerbaseEntity = await customerbaseService.GetInfo(entity.CustomerId.Value);

                //信贷管家
                CustomeruserEntity customeruserEntity = await customeruserIService.GetInfo(customerbaseEntity.Id, 1);
                //积分明细
                List<PointsdetailsEntity> pointsdetailsEntities = new List<PointsdetailsEntity>();
                //合伙人
                List<UserextendEntity> userextendEntities = new List<UserextendEntity>();

                //客户人扩展表
                UserextendEntity userextendEntity = await userextendService.GetInfoByUserId(customerbaseEntity.PartnerUserId);

                if (userextendEntity != null)
                {
                    entity.ComConfig = userextendEntity.ComConfig;
                    entity.DrawProportion = userextendEntity.DrawProportion;
                    entity.PartnerUserId = userextendEntity.UserId; ;
                    entity.ParentPartnerUserId = userextendEntity.ParentPartnerUserId;

                }
                entity.UserId = customeruserEntity.UserId;

                if (userextendEntity.PartnerNumber == null)
                {
                    userextendEntity.PartnerNumber = 0;
                }
                //只有第一次的时候，合伙人才会+1
                if (entity.Number == 1)
                {
                    userextendEntity.PartnerNumber++;  //合伙人数量+1
                                                       //取配置算积分
                }

                //当前客户没有取出配置项的时候，找出配置项，并且赋值
                if (string.IsNullOrEmpty(customerbaseEntity.ComConfig))
                {
                    List<jiushiJsconfigListOutput> configList = userextendEntity.ComConfig.Replace("\\\"", "\"").ToList<jiushiJsconfigListOutput>();
                    List<jiushiJsconfigListOutput> cusConfigList = configList.FindAll(x => userextendEntity.PartnerNumber >= x.minNumber && userextendEntity.PartnerNumber <= x.maxNumber);

                    //目前客户在那个阶段，保留 当前这个客户的配置
                    customerbaseEntity.ComConfig = cusConfigList.ToJson();

                }
                //拿到客户的配置项目再更新
                if (customerbaseEntity != null && !string.IsNullOrEmpty(customerbaseEntity.ComConfig))
                {
                    //取配置算积分
                    List<jiushiJsconfigListOutput> configList = customerbaseEntity.ComConfig.Replace("\\\"", "\"").ToList<jiushiJsconfigListOutput>();
                    if (configList != null && configList.Count > 0)
                    {
                        //算积分
                        jiushiJsconfigListOutput jiushiJsconfigList = configList.Find(x => x.min <= entity.Number && x.max >= entity.Number);

                        customerconsultantdetail.PartnerPoint = customerconsultantdetail.Amount * jiushiJsconfigList.commission / 100;
                    }
                }
                customerconsultantdetail.Type = 1;
                customerconsultantdetail.ParentPartnerUserId = entity.ParentPartnerUserId;
                customerconsultantdetail.ParentUserPoint = customerconsultantdetail.PartnerPoint * entity.DrawProportion / 100;
                customerconsultantdetail.UserId = customeruserEntity.UserId;

                //积分明细还需要添加与调整
                if (entity.PartnerUserId != null && !string.IsNullOrEmpty(entity.PartnerUserId))
                {

                    if (userextendEntity != null)
                    {
                        PointsdetailsEntity partnerPointsdetails = new PointsdetailsEntity();

                        partnerPointsdetails.PointsFront = userextendEntity.PointsPendingWithdrawal;

                        userextendEntity.TotalPointsEarned += customerconsultantdetail.PartnerPoint;
                        userextendEntity.PointsPendingWithdrawal += customerconsultantdetail.PartnerPoint;

                        userextendEntities.Add(userextendEntity);

                        partnerPointsdetails.UserId = userextendEntity.UserId;
                        partnerPointsdetails.State = 1;
                        partnerPointsdetails.Type = 1;
                        partnerPointsdetails.CustomerLoanUUID = entity.Uuid;
                        partnerPointsdetails.PublicName = customerbaseEntity.CustomerName;
                        partnerPointsdetails.Points = customerconsultantdetail.PartnerPoint;
                        partnerPointsdetails.PointsAfter = userextendEntity.PointsPendingWithdrawal;
                        partnerPointsdetails.SortCode = 0;
                        partnerPointsdetails.EnabledMark = 1;
                        partnerPointsdetails.CreatorTime = DateTime.Now;
                        partnerPointsdetails.CreatorUserId = UserProvider.Instance.Get().UserId;
                        partnerPointsdetails.CreatorUser = UserProvider.Instance.Get().UserName;
                        partnerPointsdetails.DeleteMark = 0;

                        pointsdetailsEntities.Add(partnerPointsdetails);
                    }
                }
                //上级合伙人
                if (!string.IsNullOrEmpty(entity.ParentPartnerUserId))
                {
                    UserextendEntity parentPartnerUser = await userextendService.GetInfoByUserId(entity.ParentPartnerUserId);
                    if (parentPartnerUser != null)
                    {

                        PointsdetailsEntity parentPartnerPointsdetails = new PointsdetailsEntity();
                        parentPartnerPointsdetails.PointsFront = parentPartnerUser.PointsPendingWithdrawal;



                        parentPartnerUser.TotalPointsEarned += customerconsultantdetail.ParentUserPoint;
                        parentPartnerUser.PointsPendingWithdrawal += customerconsultantdetail.ParentUserPoint;

                        userextendEntities.Add(parentPartnerUser);

                        parentPartnerPointsdetails.UserId = parentPartnerUser.UserId;
                        parentPartnerPointsdetails.State = 1;
                        parentPartnerPointsdetails.Type = 2;
                        parentPartnerPointsdetails.CustomerLoanUUID = entity.Uuid;

                        parentPartnerPointsdetails.Points = customerconsultantdetail.ParentUserPoint;
                        parentPartnerPointsdetails.PointsAfter = parentPartnerUser.PointsPendingWithdrawal;
                        parentPartnerPointsdetails.SortCode = 0;
                        parentPartnerPointsdetails.EnabledMark = 1;
                        parentPartnerPointsdetails.CreatorTime = DateTime.Now;
                        parentPartnerPointsdetails.CreatorUserId = UserProvider.Instance.Get().UserId;
                        parentPartnerPointsdetails.CreatorUser = UserProvider.Instance.Get().UserName;
                        parentPartnerPointsdetails.DeleteMark = 0;
                        parentPartnerPointsdetails.ChildUserId = entity.PartnerUserId; //子级积分 用户ID
                        UserEntity userEntity = await userService.GetInfo(parentPartnerPointsdetails.ChildUserId);
                        parentPartnerPointsdetails.PublicName = userEntity.RealName;
                        pointsdetailsEntities.Add(parentPartnerPointsdetails);


                    }
                }
                //修改数据
                await service.Create(entity, customerconsultantdetail, userextendEntities, pointsdetailsEntities, customerbaseEntity);
            }
            catch (Exception ex)
            {
                throw ExceptionEx.Throw(ex);
            }
        }


        /// <summary>
        /// 终止
        /// </summary>
        /// <param name="id">主键值</param>
        /// <returns></returns>
        public async Task End(int id)
        {
            try
            {
                CustomerconsultantEntity customerconsultantEntity = await GetInfo(id);
                customerconsultantEntity.EnabledMark = 0;

                //客户信息
                CustomerbaseEntity customerbaseEntity = await customerbaseService.GetInfo(customerconsultantEntity.CustomerId.Value);
                customerbaseEntity.EnabledMark = 0;
                customerbaseEntity.CurrentState = 3;


                UserEntity userEntity = await new UserBll().GetInfoByAccount(customerbaseEntity.MobilePhone);
                userEntity.EnabledMark = 0; //停用该账号

                UserextendEntity userextendEntity = await new UserextendBll().GetInfoByUserId(customerbaseEntity.PartnerUserId);

                userextendEntity.PartnerNumber -= 1;



                await service.End(customerconsultantEntity,customerbaseEntity, userEntity, userextendEntity);


            }
            catch (Exception ex)
            {
                throw ExceptionEx.Throw(ex);
            }
        }


        /// <summary>
        /// 更新信息
        /// </summary>
        /// <param name="id">主键值</param>
        /// <param name="entity">实体对象</param>
        /// <returns></returns>
        public async Task<int> Update(int id, CustomerconsultantEntity entity)
        {
            try
            {
                entity.Id = id;
                return await service.Update(entity);
            }
            catch (Exception ex)
            {
                throw ExceptionEx.Throw(ex);
            }
        }



        /// <summary>
        /// 删除信息
        /// </summary>
        /// <param name="entity">实体对象</param>
        /// <returns></returns>
        public async Task<int> Delete(CustomerconsultantEntity entity)
        {
            try
            {
                return await service.Delete(entity);
            }
            catch (Exception ex)
            {
                throw ExceptionEx.Throw(ex);
            }
        }

        /// <summary>
        /// 获取列表
        /// </summary>
        /// <param name="input">过滤条件</param>
        /// <returns></returns>
        public async Task<List<CustomerconsultantEntity>> GetList(jiushiCustomerconsultantListQueryInput input)
        {
            try
            {
                return await service.GetList(input);
            }
            catch (Exception ex)
            {
                throw ExceptionEx.Throw(ex);
            }
        }


    }
}